package top.laoshuzi.server.camera.mqtt

import com.alibaba.fastjson.JSON
import org.slf4j.LoggerFactory
import org.springframework.integration.mqtt.support.MqttHeaders
import org.springframework.messaging.Message
import org.springframework.messaging.MessageHandler
import org.springframework.stereotype.Component
import org.springframework.util.AntPathMatcher
import top.laoshuzi.server.camera.bean.dto.LightStateDTO
import top.laoshuzi.server.camera.config.CameraConstant
import java.lang.RuntimeException
import java.util.concurrent.ConcurrentHashMap

@Component
class MqttConsumer : MessageHandler {

    companion object {
        val lightStateMap = ConcurrentHashMap<String, LightStateDTO>()
    }

    private val logger = LoggerFactory.getLogger(MqttConsumer::class.java)

    private val antPathMatcher = AntPathMatcher()


    override fun handleMessage(message: Message<*>) {
        logger.debug("MQTT handler receiver message is ------> ${message.payload}")

        val topic = message.headers[MqttHeaders.RECEIVED_TOPIC].toString()

        if (antPathMatcher.match(CameraConstant.TOPIC_LIGHT_MATCHES, topic)) {
            val map = antPathMatcher.extractUriTemplateVariables(CameraConstant.ID_MATCHES, topic)
            lightStateMap[map["id"]
                    ?: throw RuntimeException("id 不能为空")] = JSON.parseObject(message.payload.toString(), LightStateDTO::class.java)
        }

    }


}
